package com.xxx.reggie.controller;

import com.xxx.reggie.common.R;
import com.xxx.reggie.entity.User;
import com.xxx.reggie.service.UserService;
import com.xxx.reggie.util.SMSUtils;
import com.xxx.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired(required = false)
    private RedisTemplate<String,String> redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //接收的手机号存入User中
        //生成四位数的手机号码
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        System.out.println("验证码:"+code);

        //3.发送手机短信验证码
        //SMSUtils.sendMessage("黑马旅游网","SMS_198917972","18720897033",code);

        //4.将生成的验证码存入session中(手机号作为Kay,验证码作为value)
        //session.setAttribute(user.getPhone(),code);
        redisTemplate.opsForValue().set(user.getPhone(),code,5, TimeUnit.MINUTES);

        //5.返回数据
        return R.success("验证码已发送");
    }

    @Autowired(required = false)
    private UserService userService;

    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String,String> map,HttpSession session){
        //1.接收数据封装到Map<String,String> map中
        String phone = map.get("phone");
        String code = map.get("code");
        //2.从session中获取存储的验证码
        //String phoneCode = (String) session.getAttribute(phone);
        String phoneCode = redisTemplate.opsForValue().get(phone);
        //3.调用业务层进行登入操作,返回登入的用户对象
        User userLogin = userService.UserByPhone(phone, code, phoneCode);
        //4.登入用户有效,写入session(key="user")
        if(userLogin!=null){

            redisTemplate.delete(phone);

            session.setAttribute("user",userLogin);
        }
        //5.返回数据(登入的用户)
        return R.success(userLogin);
    }

}
